
package com.an.framework;

import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.an.framework.interceptor.ProcessTimeInterceptor;

/**
 * @author 86171
 *
 *         Spring mvc的配置
 */
/*
 * 继承WebMvcConfigurerAdapter类，重写其方法可对Spring Mvc进行配置
 *
 */
@ComponentScan("com.an") // 启用组件扫描
@Configuration
@EnableWebMvc // 开启springmvc支持，若无此重写WebMvcConfigurerAdapter方法无效
@EnableAsync // 开启多线程支持
@EnableScheduling // 开启定时任务的支持
public class SpringMvcConfig implements WebMvcConfigurer, AsyncConfigurer {

	// 视图解析，配置JSP视图解析器
	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		// 这是干嘛的呢？？
		viewResolver.setExposeContextBeansAsAttributes(true);
		viewResolver.setViewClass(JstlView.class);
		return viewResolver;
	}

	// 静态资源映射，这个主要是提高性能
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 对外暴露访问路径addResourceHandler
		// 文件放置位置addResourceLocations
		registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
	}

	// 增加自定义拦截器
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(processTimeInterceptor());
	}

	// 请求处理时间计算拦截器
	@Bean
	public ProcessTimeInterceptor processTimeInterceptor() {
		return new ProcessTimeInterceptor();
	}

	public Executor getAsyncExecutor() {
		// 任务线程池
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setMaxPoolSize(20);
		executor.setCorePoolSize(5);
		executor.setQueueCapacity(25);
		executor.initialize();
		return executor;
	}

	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return null;
	}

}
